<template>
  <div style="width: 100vw; height: 100vh; margin: 0 auto; overflow: hidden">
    <svg-prview
      :component_infos="component_infos"
      :svg_data="prview_data"
      :svgCanvas="{ width: tWidth, height: tHeight }"
      :backgroundColor="tBackgroundColor"
      :token="token"
    ></svg-prview>
  </div>
</template>

<script setup lang="ts">
import SvgPrview from "../components/SvgPrview.vue";
import axios from "axios";
import { reactive, ref } from "@vue/reactivity";
import { useRoute } from "vue-router";
import Cookies from "js-cookie";
import { getCurrentInstance, inject, onMounted, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import { getList, getTopoById, getPointDefalut } from "../api/business";
import { defineComponent } from "vue";

const mqtt: any = inject("$m");
const route = useRoute();
const nodeList: Array<any> = reactive([]); //页面点位数组
const valueList = reactive([]); //接口获取点位数据数组
const tid = route.query[Object.keys(route.query)[0]];
const token = ref(null);
function getURLParameter(name) {
  console.log(window.location, "window.location.search");
  const hashPath = window.location.hash.split("?")[0];
  console.log("Hash Path:", hashPath); // #/prview
  // 获取哈希片段中的查询参数
  const hashQueryParams = new URLSearchParams(
    window.location.hash.split("?")[1]
  );
  return hashQueryParams.get(name);
}
// 使用函数获取参数
 token.value = getURLParameter("token");
// SSE 连接处理（基地址从环境获取）
let sseRef: EventSource | null = null;

// 解析SSE消息数据：提取JSON数组部分
const parseSseData = (rawData: string): Array<any> => {
  try {
    // 格式：[时间戳] Data #[{...}]
    const jsonMatch = rawData.match(/Data\s*#\s*(\[.*\])/);
    if (jsonMatch && jsonMatch[1]) {
      return JSON.parse(jsonMatch[1]);
    }
    // 如果直接是JSON数组，尝试直接解析
    const trimmed = rawData.trim();
    if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
      return JSON.parse(trimmed);
    }
  } catch (err) {
    console.error("SSE数据解析失败:", err, rawData);
  }
  return [];
};

// 处理SSE消息数据，更新组件
const handleSseData = (dataList: Array<any>) => {
  if (!dataList || dataList.length === 0) return;
  
  // 更新valueList
  valueList.length = 0;
  valueList.push(...dataList);
  
  // 更新所有组件（复用MQTT的处理逻辑）
  nodeList.forEach((node) => {
    if (node["type"] === "single") {
      //单点位处理
      valueList.forEach((value) => {
        if (value.nodeKey) {
          if (value.nodeKey.trim() === node.nodeKey.trim()) {
            handelSingleNodeKey(
              node.svg,
              value.nodeValue ||
                value.originNodeValue ||
                value.transformNodeValue
            ); //单点位处理函数
            if (node["svg"]["title"] == "仪表盘") {
              //单点雷达图处理
              handelLDT(
                node["svg"],
                value.nodeValue ||
                  value.originNodeValue ||
                  value.transformNodeValue
              );
            }
          }
        }
      });
    } else if (node["type"] === "mutlPoint") {
      //多点位处理
      valueList.forEach((value) => {
        node.nodeKey.forEach((key, i) => {
          if (value.nodeKey.trim() === key.trim()) {
            node.svg.valList[i] =
              value.nodeValue ||
              value.originNodeValue ||
              value.transformNodeValue;
          }
        });
      });
      handelMutlNodeKey(node.svg, node.svg.valList); //多点位处理函数
    } else if (node["type"] === "mutlGroup") {
      //多组多点位处理
      if (node["svg"]["title"].indexOf("Echart") !== -1) {
        //图表处理
        let updataFlag = false;
        if (Array.isArray(node.chartData[0])) {
          //有多组y轴数据
          node.chartData.forEach((chart) => {
            chart.forEach((c) => {
              //多一层循环
              valueList.forEach((value) => {
                if (value.nodeKey.trim() === c.nodeKey.trim()) {
                  updataFlag = true;
                  c.nodeValue =
                    value.nodeValue ||
                    value.originNodeValue ||
                    value.transformNodeValue; //更改图表绑定数据
                }
              });
            });
          });
        } else {
          //单组Y轴数据
          node.chartData.forEach((chart) => {
            valueList.forEach((value) => {
              if (value.nodeKey.trim() === chart.nodeKey.trim()) {
                updataFlag = true;
                chart.nodeValue =
                  value.nodeValue ||
                  value.originNodeValue ||
                  value.transformNodeValue; //更改图表绑定数据
              }
            });
          });
        }
        if (updataFlag) {
          updateChart(node);
        }
      }
    }
  });
};

onMounted(() => {
  try {
    const base = (import.meta as any).env?.VITE_HTTP_BASE || "/dev-api";
    const baseNorm = String(base).replace(/\/$/, "");
    const qs = new URLSearchParams();
    if (token.value) qs.set('token', String(token.value));
    const sseUrl = `${baseNorm}/intra/iot/sse/stream${qs.toString() ? `?${qs.toString()}` : ''}`;
    const es = new EventSource(sseUrl);
    sseRef = es;
    
    es.onopen = () => {
      console.log("SSE opened:", sseUrl);
    };
    
    // 监听自定义事件 "message"（后端发送 event:message）
    es.addEventListener("message", (e: MessageEvent) => {
      console.log("SSE message event:", e.data);
      const dataList = parseSseData(e.data);
      if (dataList.length > 0) {
        handleSseData(dataList);
      }
    });
    
    // 也可以监听默认的message事件（兼容）
    es.onmessage = (e) => {
      console.log("SSE default message:", e.data);
      const dataList = parseSseData(e.data);
      if (dataList.length > 0) {
        handleSseData(dataList);
      }
    };
    
    es.onerror = (e) => {
      console.warn("SSE error:", e);
    };
  } catch (err) {
    console.error("SSE init failed:", err);
  }
});

onUnmounted(() => {
  if (sseRef) {
    try { sseRef.close(); } catch {}
    sseRef = null;
  }
});
const handelSingleNodeKey = (svg, value) => {
  //处理单点位svg数据逻辑

  let mutlNodeFlag = false; //用来判断是不是多点位
  if (Array.isArray(value)) {
    mutlNodeFlag = true;
  }
  //进制转换特性
  if (svg.active.hasOwnProperty("active_conversion")) {
    let con = svg.active.active_conversion.alarm[0].conversion.val.selectval;
    let index = svg.active.active_conversion.alarm[0].expression.val;
    if (con == 2) {
      //二进制转换
      if (mutlNodeFlag)
        //如果是多点位
        value[index] = value[index].toString(2);
      else {
        value = parseInt(value).toString(2).split("").reverse();
        for (let i = 0; i < 10; i++) {
          //二进制补0
          value.push(0);
        }
      }
    } else if (con == 16) {
      //十六进制转换
      if (mutlNodeFlag)
        //如果是多点位
        value[index] = value[index].toString(16);
      else value = parseInt(value).toString(16).split("").reverse();
    }
  }
  if (svg.type === "TextSvg") {
    //文本直接赋值
    if (
      svg.active.hasOwnProperty("active_DVtrans") &&
      svg.active.active_DVtrans.val.selectval
    ) {
      //判断是否有值转动态属性
      let text = eval(svg.active.active_DVtrans.alarm[0].expression.val);
      svg.extend_attr.text.val = text;
    } else {
      if (mutlNodeFlag) {
        //如果是多点位,默认绑定最后一个
        svg.extend_attr.text.val = value[value.length - 1];
      } else {
        svg.extend_attr.text.val = value;
      }
    }
  }
  //动态属性

  if (
    svg.active.hasOwnProperty("active_color") &&
    svg.active?.active_color?.val?.selectval
  ) {
    svg.active.active_color.alarm.forEach((kk) => {
      if (eval(kk.expression.val)) {
        if (svg.extend_attr.color) svg.extend_attr.color.val = kk.color.val;
        else if (svg.extend_attr.fill) svg.extend_attr.fill.val = kk.color.val;
        else if (svg.extend_attr.fillcolor)
          svg.extend_attr.fillcolor.val = kk.color.val;
      }
    });
  }

  //switch效果状态
  if (svg.active.hasOwnProperty("active_switch")) {
    svg.active.active_switch.alarm.forEach((kk) => {
      if (eval(kk.expression.val)) {
        svg.extend_attr.switch.val.selectval = kk.switch.val.selectval;
      }
    });
  }

  //旋转效果，动画方式
  if (svg.active?.active_rotate?.val?.selectval) {
    svg.active.active_rotate.alarm.forEach((kk) => {
      if (eval(kk.expression.val)) {
        svg.extend_attr.class.val = kk.animation.val.selectval;
      }
    });
  }
  //旋转效果，变换方式translate
  if (svg.active?.active_translate_rotate?.val?.selectval) {
    svg.active.active_translate_rotate.alarm.forEach((kk) => {
      if (eval(kk.expression.val)) {
        svg.angle = kk.angle.val;
      }
    });
  }
  //图片切换
  if (svg.active?.active_changeSrc?.val?.selectval) {
    svg.active.active_changeSrc.alarm.forEach((kk) => {
      if (eval(kk.expression.val)) {
        svg.extend_attr.src.val = kk.src.val;
      }
    });
  }

  //显示、隐藏
  if (svg.active?.active_show?.val?.selectval) {
    svg.active.active_show.alarm.forEach((kk) => {
      if (eval(kk.expression.val)) {
        svg.extend_attr.show.val = kk.show.val.selectval;
      }
    });
  }
  //X位移
  if (svg.active?.active_Xtranslate?.val?.selectval) {
    let xLastPosition = svg.active.active_Xtranslate.lastPosition; //上次的位置
    let xStep = svg.active?.active_Xtranslate?.alarm[0].expression.val; //x轴位移步长
    let val = 0; //实际位移绑点值
    if (mutlNodeFlag) {
      //多点的话需要确定是哪个点
      val = parseFloat(
        eval(svg.active?.active_Xtranslate?.alarm[1].expression.val)
      );
    } else val = parseFloat(value);
    let len = val - parseFloat(xLastPosition);

    svg.svgPositionX += len * parseFloat(xStep);
    svg.active.active_Xtranslate.lastPosition = parseFloat(value);
  }
};
const handelMutlNodeKey = (svg, valList) => {
  handelSingleNodeKey(svg, valList);
};
const initChart = (node) => {
  let xData = []; //x轴数据
  let yData = []; //y轴数据
  let chartData = []; //node里存入chartData
  let option = JSON.parse(node["svg"].extend_attr.echarts_option.val);
  if (Array.isArray(node["nodeKey"][0])) {
    node["nodeKey"].forEach((keyList, i) => {
      let arr = [];
      let chartArr = [];
      keyList.forEach((key) => {
        valueList.forEach((v) => {
          if (key.trim() === v.nodeKey.trim()) {
            // 如果没有 deviceName，使用 nodeKey 作为名称
            const displayName = v.deviceName || v.nodeKey.split('@')[0] || v.nodeKey;
            xData.push(displayName);
            arr.push(v.nodeValue);
            chartArr.push({
              nodeKey: key,
              name: displayName,
              nodeValue: v.nodeValue,
            });
          }
        });
      });
      option.series[i].data = arr;
      chartData.push(chartArr);
    });
  } else {
    node["nodeKey"].forEach((key) => {
      valueList.forEach((v) => {
        if (key.trim() === v.nodeKey.trim()) {
          // 如果没有 deviceName，使用 nodeKey 作为名称
          const displayName = v.deviceName || v.nodeKey.split('@')[0] || v.nodeKey;
          xData.push(displayName);
          yData.push(v.nodeValue);
          chartData.push({
            nodeKey: key,
            name: displayName,
            nodeValue: v.nodeValue,
          });
        }
      });
      option.series[0].data = yData;
    });
  }

  option.xAxis.data = xData;

  node.chartData = chartData; //nodeKey绑定图表数据
  node["svg"].extend_attr.echarts_option.val = JSON.stringify(option);
};
const updateChart = (node) => {
  let yData = [];
  let option = JSON.parse(node["svg"].extend_attr.echarts_option.val);
  if (Array.isArray(node.chartData[0])) {
    node.chartData.forEach((chart, i) => {
      let arr = [];
      chart.forEach((c) => {
        arr.push(c.nodeValue);
      });
      option.series[i].data = arr;
    });
  } else {
    node.chartData.forEach((chart) => {
      yData.push(chart.nodeValue);
    });
    option.series[0].data = yData;
  }
  node["svg"].extend_attr.echarts_option.val = JSON.stringify(option);
};
//处理仪表盘数据
const handelLDT = (svg: any, value: any) => {
  let option = JSON.parse(svg.extend_attr.echarts_option.val);
  option.series[1].data[0].value = value;
  svg.extend_attr.echarts_option.val = JSON.stringify(option);
};
//页面初始化接口,需要传nodeKey数组
const initData = (nodeList: Array<Object>) => {
  let nodeKeyList: Array<String> = [];
  (nodeList as Array<Object>).forEach((e) => {
    if (e["type"] === "mutlGroup") {
      //多组多点位
      if (Array.isArray(e["nodeKey"][0])) {
        e["nodeKey"].forEach((k) => {
          nodeKeyList.push(...k);
        });
      }
    } else if (e["type"] === "mutlPoint") {
      //多点位
      nodeKeyList.push(...e["nodeKey"]);
    } //单点位
    else if (e["nodeKey"] !== "mouseRect") nodeKeyList.push(e["nodeKey"]);
  });
  getPointDefalut({ nodeKeyList }, token.value)
    .then((res) => {
      if (res.code === 200 && res.data.length) {
        valueList.length = 0;
        valueList.push(...res.data);
        nodeList.forEach((node) => {
          if (node["type"] === "single") {
            //先处理单点位绑定的svg，多点位额外处理
            valueList.forEach((data) => {
              if (
                data.nodeKey.trim() === node["nodeKey"].trim() &&
                data.nodeValue !== null &&
                data.nodeValue !== undefined
              ) {
                if (node["svg"]["title"] == "仪表盘") {
                  //单点仪表盘处理
                  handelLDT(node["svg"], data.nodeValue);
                }
                handelSingleNodeKey(node["svg"], data.nodeValue);
              }
            });
          } //处理多点位
          else {
            if (node["type"] === "mutlGroup") {
              //处理多组多点位
              if (node["svg"]["title"].indexOf("Echart") !== -1)
                //图表单独处理
                initChart(node);
            } else if (node["type"] === "mutlPoint") {
              //处理多点位
              let valList = [];
              node["nodeKey"].forEach((key) => {
                valueList.forEach((data) => {
                  if (
                    data.nodeKey.trim() === key.trim() &&
                    data.nodeValue !== null &&
                    data.nodeValue !== undefined
                  ) {
                    valList.push(data.nodeValue);
                  }
                });
              });
              node["svg"].valList = valList; //多点位初始化
              handelMutlNodeKey(node["svg"], valList);
            }
          }
        });
        mqtt_info();
      }
    })
    .catch((error) => {
      ElMessage({
        type: "error",
        message: "初始化失败，请检查!" + error,
      });
    });
};

//图库json数据
const component_infos = ref([]);
//要预览的数据
const prview_data = ref<any>([]);
//当前页面的toptic的数组
const topicList = ref("");
//获取组件列表
axios.get("json/InterfaceReturn.json").then((res) => {
  component_infos.value = res.data;
});
let tWidth = ref(1710);
let tHeight = ref(860);
let tBackgroundColor = ref(null); //画布背景颜色
//传入参数，获取页面数据
if ("" != tid) {
  // const backendUrl = getCurrentInstance()?.appContext.config.globalProperties.$backendUrl
  getTopoById(tid, token.value).then((res) => {
    if (res.code == 200 && res.data != "") {
      tWidth.value = (res.data[0] as any).t_width;
      tHeight.value = (res.data[0] as any).t_height;
      var svgdata = (res.data[0] as any).t_jsondata;
      prview_data.value = JSON.parse(svgdata);
      // prview_data.value = res.data;
      topicList.value = (res.data[0] as any).t_topic;
      tBackgroundColor.value = (res.data[0] as any).t_background_color;
      getDefaultConfig();
    } else {
      alert("调用后端失败");
    }
  });
}

//有动态效果的文字SVG
const TextSvgList = ref<any>([]);
//有动态效果的非文字SVG
const allActiveList = ref<any>([]);
//获取本页面默认数据列表
const getDefaultConfig = () => {
  let temp: Array<any> = [...prview_data.value];
  //找到所有的文字
  TextSvgList.value = temp.filter(
    (f) => f.active_type == "text" && f.nodeKey !== ""
  );
  allActiveList.value = temp.filter((f) => f.nodeKey !== "");
  allActiveList.value.forEach((e) => {
    if (e.nodeKey.indexOf(",") === -1) {
      nodeList.push({ id: e.id, type: "single", nodeKey: e.nodeKey, svg: e }); //单个点位直接入数组
    } else {
      if (e.nodeKey.indexOf("|") !== -1) {
        let arrList = [];
        let keyList = [];
        arrList = e.nodeKey.split("|");
        arrList.forEach((e) => {
          if (e.length) keyList.push(e.split(","));
        });
        nodeList.push({
          id: e.id,
          type: "mutlGroup",
          nodeKey: keyList,
          svg: e,
        }); //多组多点位数组
      } else
        nodeList.push({
          id: e.id,
          type: "mutlPoint",
          nodeKey: e.nodeKey.split(","),
          svg: e,
        }); //多点位拆分入node
    }
  });
  initData(nodeList); //页面统一初始化接口
};
const mqtt_info = () => {
  let topic = [];
  topic = topicList.value.split(",");
  mqtt.subscribe(topic, 0); //订阅topic
  topic.forEach((t) => {
    mqtt.message_callback(t, (topic: string, payload: Buffer) => {
      let payloadData = JSON.parse(payload.toString());

      valueList.length = 0;
      valueList.push(...payloadData);
      nodeList.forEach((node) => {
        if (node["type"] === "single") {
          //单点位处理
          valueList.forEach((value) => {
            if (value.nodeKey) {
              if (value.nodeKey.trim() === node.nodeKey.trim()) {
                handelSingleNodeKey(
                  node.svg,
                  value.nodeValue ||
                    value.originNodeValue ||
                    value.transformNodeValue
                ); //单点位处理函数
                if (node["svg"]["title"] == "仪表盘") {
                  //单点雷达图处理
                  handelLDT(
                    node["svg"],
                    value.nodeValue ||
                      value.originNodeValue ||
                      value.transformNodeValue
                  );
                }
              }
            }
          });
        } else if (node["type"] === "mutlPoint") {
          //多点位处理

          valueList.forEach((value) => {
            node.nodeKey.forEach((key, i) => {
              if (value.nodeKey.trim() === key.trim()) {
                node.svg.valList[i] =
                  value.nodeValue ||
                  value.originNodeValue ||
                  value.transformNodeValue;
              }
            });
          });
          handelMutlNodeKey(node.svg, node.svg.valList); //单点位处理函数
        } else if (node["type"] === "mutlGroup") {
          //多组多点位处理
          if (node["svg"]["title"].indexOf("Echart") !== -1) {
            //图表处理
            let updataFlag = false;
            if (Array.isArray(node.chartData[0])) {
              //有多组y轴数据
              node.chartData.forEach((chart) => {
                chart.forEach((c) => {
                  //多一层循环
                  valueList.forEach((value) => {
                    if (value.nodeKey.trim() === c.nodeKey.trim()) {
                      updataFlag = true;
                      c.nodeValue =
                        value.nodeValue ||
                        value.originNodeValue ||
                        value.transformNodeValue; //更改图表绑定数据
                    }
                  });
                });
              });
            } else {
              //单组Y轴数据
              node.chartData.forEach((chart) => {
                valueList.forEach((value) => {
                  if (value.nodeKey.trim() === chart.nodeKey.trim()) {
                    updataFlag = true;
                    chart.nodeValue =
                      value.nodeValue ||
                      value.originNodeValue ||
                      value.transformNodeValue; //更改图表绑定数据
                  }
                });
              });
            }
            if (updataFlag) {
              updateChart(node);
            }
          }
        }
      });
    });
  });
};
</script>
